//
//  WBMainController.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/6.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

/*
 extension的用法：
 1. 扩展类的功能
 2. 遵循协议，实现代理
 3. 代码分组
    分组原则：UI， 数据， 事件， 代理和协议， class里面只放属性和生命周期函数
 
 */

class WBMainController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        self.setupUI()
    }
}

// MARK: - 设置UI
extension WBMainController {
    
    /// 设置UI
    func setupUI () {
        //1. 添加所有的子控制器
        addControllers()
        //2. 添加发布按钮
        addComposeButton()
        //3. 添加访客视图或新特性页
        if WBUserAccount.shared.isLogin {
            addWelcomeOrNewfeature()
        }
    }
    
    /// 添加访客视图或者是新特性页
    func addWelcomeOrNewfeature() {
        let isNewFeature = Bundle.isNewFeature()
        if isNewFeature {
            let newFeature = WBNewFeature()
            view.addSubview(newFeature)
        } else {
            let welcome = WBWelcomeView()
            view.addSubview(welcome)
        }
    }
    
    /// 添加所有的子控制器
    func addControllers() {
        //1. 从沙盒中获取到json
        let path = Bundle.main.path(forResource: "main.json", ofType: nil)
        let url = URL(fileURLWithPath: path!)
        let jsonData = try! Data(contentsOf: url)
        
        //2. json解析
        let dicArr = try? JSONSerialization.jsonObject(with: jsonData)
        
        //此时dicArr是一个Any类型
        if let dicArr = dicArr {
            //print(dicArr)
            var navControllers = [UINavigationController]()
            
            //3. for循环创建子控制器
            for dic in dicArr as! [[String: Any]] {
                let navController = childController(dic)
                navControllers.append(navController)
            }
            viewControllers = navControllers
        }
    }
    
    
    /// 创建一个子控制器(navigationController)
    ///
    /// - Parameter withDic: 子控制器的参数字典
    /// - Returns: navigationController
    func childController(_ withDic: [String: Any]) -> UINavigationController {
        //获取类名，title，图片名
        let className = withDic["clsName"] as! String
        let fullClassName = "WeiboTen."+className
        let title = withDic["title"] as! String
        let imageName = withDic["imageName"] as! String

        //获取到创建子控制器的类
        let controllerCls = NSClassFromString(fullClassName) as! WBRootController.Type
        //创建一个子控制器
        let controller = controllerCls.init()
        
        //获取访客视图的title和图标的参数字典
        controller.visitorInfo = withDic["visitorInfo"] as? [String : Any]
        
        //设置title
        controller.title = title
        controller.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], for: .selected)
        controller.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
        
        //设置图片
        controller.tabBarItem.image = UIImage(named: "tabbar_\(imageName)")?.withRenderingMode(.alwaysOriginal)
        controller.tabBarItem.selectedImage = UIImage(named: "tabbar_\(imageName)_selected")?.withRenderingMode(.alwaysOriginal)

        //创建并返回子控制器
        let navController = UINavigationController(rootViewController: controller)
        return navController
    }
    
    func addComposeButton () {
        //添加发布按钮
        let button = UIButton(text: nil, image: "tabbar_compose_icon_add", bgImage: "tabbar_compose_button", target: self, selector: #selector(composeButton(button:)))
        
        let insetX = tabBar.bounds.size.width / 5 * 2 - 1
        let rect = tabBar.bounds.insetBy(dx: insetX, dy: 5)
        button.frame = rect
        
        tabBar.addSubview(button)
    }
}


// MARK: - 事件处理
extension WBMainController {
    @objc func composeButton (button: UIButton) {
        //如果没有登录，弹出登录页面  testDebug
//        if WBUserAccount.shared.isLogin {
            let compose = WBComposeController()
            let navCompose = UINavigationController(rootViewController: compose)
            present(navCompose, animated: true, completion: nil)
//        } else {
//            //推出一个登录的控制器
//            let loginvc = WBLoginController()
//            let loginNav = UINavigationController(rootViewController: loginvc)
//            present(loginNav, animated: true, completion: nil)
//        }
    }
}
